<?php
// $Id$

/**
 * Smslog 封装来自 sms_log 数据表的记录及领域逻辑
 */
class paperquestion extends QDB_ActiveRecord_Abstract
{

    /**
     * 返回对象的定义
     *
     * @static
     *
     * @return array
     */
    static function __define()
    {
        return array
        (
            // 指定该 ActiveRecord 要使用的行为插件
            'behaviors' => '',

            // 指定行为插件的配置
            'behaviors_settings' => array
            (
                # '插件名' => array('选项' => 设置),
            ),

            // 用什么数据表保存对象
            'table_name' => 'edu_paper_questions',

            // 指定数据表记录字段与对象属性之间的映射关系
            // 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
            'props' => array
            (
                // 主键应该是只读，确保领域对象的“不变量”
                'id' => array('readonly' => true),

                // 对象创建时间应该是只读
                'created' => array('readonly' => true),


                /**
                 *  可以在此添加其他属性的设置
                 */
                # 'other_prop' => array('readonly' => true),

                /**
                 * 添加对象间的关联
                 */
                # 'other' => array('has_one' => 'Class'),
//          'agent'=>array('has_one'=>'acct','source_key'=>'agent_id','target_id'=>'id'),
//             'admin'=>array('has_one'=>'acct','source_key'=>'admin_id','target_id'=>'id')

            ),

            /**
             * 允许使用 mass-assignment 方式赋值的属性
             *
             * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
             */
            'attr_accessible' => '',

            /**
             * 拒绝使用 mass-assignment 方式赋值的属性
             */
            'attr_protected' => 'id',

            /**
             * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
             *
             * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
             */
            'create_reject' => '',

            /**
             * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
             */
            'update_reject' => '',

            /**
             * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
             *
             * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
             * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
             *
             * 如果填充值为一个数组，则假定为 callback 方法。
             */
            'create_autofill' => array
            (
                # 属性名 => 填充值
                # 'is_locked' => 0,
                
                'created' => self::AUTOFILL_TIMESTAMP ,
            ),

            /**
             * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
             *
             * 填充值的指定规则同 create_autofill
             */
            'update_autofill' => array
            (
            ),

            /**
             * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
             *
             * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
             *
             * 如果需要添加一个自定义验证，应该写成
             *
             * 'title' => array(
             *        array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
             * )
             *
             * 然后在该类中添加 checkTitle() 方法。函数原型如下：
             *
             * static function checkTitle($title)
             *
             * 该方法返回 true 表示通过验证。
             */
            'validations' => array
            (
                
            ),
        );
    }


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

    /**
     * 开启一个查询，查找符合条件的对象或对象集合
     *
     * @static
     *
     * @return QDB_Select
     */
    static function find()
    {
        $args = func_get_args();
        return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
    }

    /**
     * 返回当前 ActiveRecord 类的元数据对象
     *
     * @static
     *
     * @return QDB_ActiveRecord_Meta
     */
    static function meta()
    {
        return QDB_ActiveRecord_Meta::instance(__CLASS__);
    }


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */

    //获取sub信息 type--0章节题目1综合题
    static function getsubjectinfo($questions_id){
        if(empty($questions_id)){
            return false;
        }
        $host = Helper_Common::getRequestHost();
       			$filename = Q::ini('app_config/ROOT_DIR').'/config/redis.yaml';
			$config = Helper_YAML::load($filename);
			$redis = new Redis();
			$redis->pconnect($config['host'],$config['port']);
        $rv = $redis->get("edulive:$host:question_info:".$questions_id);
        if(!empty($rv)){
            return json_decode($redis->get("edulive:$host:question_info:".$questions_id),true);
        }else{

            $question = paperquestion::find("id = ".$questions_id)->getOne();
            $paper_id = $question->paper_id;
            $paper_info = paper::find("id = ".$paper_id)->getOne();
            $data['paper_id']=$paper_id;
            if($paper_info->generalcourse_id>0){
                $data['type']=1;
                $generalcourse = papergeneralcourse::find("id = ".$paper_info->generalcourse_id)->getOne();
                $data['generalcourse_id']=$paper_info->generalcourse_id;
                $data['subject_id']=$generalcourse->subject_id;
                //$subject_id = 
            }else{
                $data['type']=0;
                $chapter = papercoursechapter::find("id = ".$paper_info->chapter_id)->getOne();
                $course = papercourse::find("id = ".$chapter->course_id)->getOne();
                $data['chapter_id']=$paper_info->chapter_id;
                $data['course_id']=$chapter->course_id;
                $data['subject_id']=$course->subject_id;
            }
            $redis->set("edulive:$host:question_info:".$questions_id,json_encode($data));
            $redis->expire("edulive:$host:question_info:".$questions_id,86400);
            $redis->close();
            return $data;
        }


    }

    static function getlistforid($pid,$uid,$question_id,$dolog_id=0){

        $sql = "SELECT
            q.*
        FROM
            edu_paper_questions AS q 
        WHERE
            q.id = $question_id";
        $question = QDB::getConn()->execute($sql)->fetchAll();
        for ($i=0; $i < count($question); $i++) { 
            $question[$i]['answer'] = strtoupper($question[$i]['answer']);
            $question[$i]['is_collect'] = papersubjectcollection::getcollectstatus($question[$i]['paper_id'],$uid,$question[$i]['id']);
            //填空题
           $question[$i]['kaodian'] = explode(',', $question[$i]['kaodian']);

            if($dolog_id){
                $question[$i]['oanswer'] = paperquestiondolog::find("id=?",$dolog_id)->getOne()->answer;
            }
        }
        return $question;
    }


    //试题列表
    static function getlist($pid,$uid){

        $sql = "SELECT
            q.*
        FROM
            edu_paper_questions AS q 
        WHERE
            q.paper_id = $pid ";

        $question = QDB::getConn()->execute($sql)->fetchAll();
        for ($i=0; $i < count($question); $i++) { 
            $question[$i]['answer'] = strtoupper($question[$i]['answer']);
            $question[$i]['is_collect'] = papersubjectcollection::getcollectstatus($pid,$uid,$question[$i]['id']);
            $question[$i]['kaodian'] = explode(',', $question[$i]['kaodian']);
        }
        return $question;
    }
    //试题列表做题记录
    static function questionlistexam($pid,$exam_id,$uid){

        $sql = "SELECT
            q.*,
            b.answer as oanswer,
            b.isright
        FROM
            edu_paper_questions AS q 
            LEFT JOIN edu_paper_questions_dolog AS b ON ( b.exam_id = $exam_id AND q.id = b.questions_id ) 
        WHERE
            q.paper_id = $pid ";
        $question = QDB::getConn()->execute($sql)->fetchAll();
        for ($i=0; $i < count($question); $i++) { 
            $question[$i]['answer'] = strtoupper($question[$i]['answer']);
            $question[$i]['oanswer'] = strtoupper($question[$i]['oanswer']);
            $question[$i]['kaodian'] = explode(',', $question[$i]['kaodian']);
            $question[$i]['is_collect'] = papersubjectcollection::getcollectstatus($pid,$uid,$question[$i]['id']);
        }
        return $question;
    }

    //交卷
    static function submitpaper($info,$user_id,$acct_id,$startdo_time=0,$type=1){

        if($info){
            $info = json_decode($info,true);
            if(count($info)>0){
                $sub = paperquestion::getsubjectinfo($info[0]['id']);
                $user = acctuser::find('id=?',$user_id)->getOne();
                //创建考试记录
                $exam_data=array(
                    "paper_id"=>$sub['paper_id'],
                    "user_id"=>$user_id,
                    "subject_id"=>$sub['subject_id'],
                    "startdo_time"=>$startdo_time,
                    "nickname"=>$user->id()?$user->nickname:'',
                    "id_card_num"=>$user->id()?$user->id_card_num:'',
                    "real_name"=>$user->id()?$user->real_name:'',
                    "phone"=>$user->id()?$user->phone:'',
                    "hand_time"=>time(),
                    "type"=>$type
                );
                $exam = new paperexam($exam_data);
                $exam->save();
                $exam_id = $exam->id;
            }
            
            
            for ($i=0; $i < count($info); $i++) { 
                if(empty($info[$i]['checked'])){
                    $info[$i]['checked'] = '';

                }else{
                    sort($info[$i]['checked']);
                    $info[$i]['checked'] = implode('', $info[$i]['checked']);
                }
                //添加答题记录
                $data=array(
                    "user_id"=>$user_id,
                    "paper_id"=>$sub['paper_id'],
                    "questions_id"=>$info[$i]['id'],
                    "answer"=>empty($info[$i]['checked'])?'':$info[$i]['checked'],
                    "is_do"=>empty($info[$i]['checked'])?0:1,
                    "isright"=>$info[$i]['checked']==strtoupper($info[$i]['answer']) && $info[$i]['answer'] ?1:0,
                    "exam_id"=>$exam_id
                );
                $dolog = new paperquestiondolog($data);
                $dolog->save();
                //添加错题记录
                if($info[$i]['checked']!="" && strtoupper($info[$i]['checked'])!=strtoupper($info[$i]['answer']) ){
                    $data = array(
                        "acct_id"=>$acct_id,
                        "user_id"=>$user_id,
                        "paper_id"=>$sub['paper_id'],
                        "subject_id"=>$sub['subject_id'],
                        "type"=>$sub['type'],
                        "questions_id"=>$info[$i]['id'],
                        "generalcourse_id"=>$sub['type']==1?$sub['generalcourse_id']:0,
                    );
                    $mistake = new papersubjectmistakes($data);
                    $mistake->save();
                }
            }
            return $exam_id;
        }
        
    }
    //xls导入试题
    static function importquestion($xls,$paper_id){
        $arr = paperquestion::readxls($xls);
        $question_number=paperquestion::find("paper_id = ".$paper_id)->getCount();
        // $type = paper::getpapertype($paper_id);
        $paper = paper::find("id = ".$paper_id)->getOne();
        $acct_id = $paper->acct_id;
        for ($i=0; $i < count($arr); $i++) { 
            if(!empty($arr[$i][0])){
                $data=array(
                    "paper_id"=>$paper_id,
                    "acct_id"=>$acct_id,
                    "question_number"=>$question_number+1+$i,
                    "type"=>$paper->type,
                    "title"=>empty($arr[$i][0])?'':$arr[$i][0],
                    "optiona"=>empty($arr[$i][1])?'':$arr[$i][1],
                    "optionb"=>empty($arr[$i][2])?'':$arr[$i][2],
                    "optionc"=>empty($arr[$i][3])?'':$arr[$i][3],
                    "optiond"=>empty($arr[$i][4])?'':$arr[$i][4],
                    // "optione"=>empty($arr[$i][5])?'':$arr[$i][5],
                    "answer"=>paperquestion::formatanswer($arr[$i][5]),
                    "resolution"=>empty($arr[$i][6])?'':$arr[$i][6],
                    "kaodian"=>empty($arr[$i][7])?'':str_replace('，', ',',trim($arr[$i][7])),
                );
                $question = new paperquestion($data);
                $question->save();
            }
        }
    }
    static function formatanswer($answer){
        if(empty($answer)){
            return '';
        }
        $str = strtoupper(str_replace(',', '', str_replace('，', ',', trim($answer)) ));
        $arr = str_split($str);
        sort($arr);
        return implode('', $arr);

    }

    static function readxls($xls){
        require_once('../lib/Classes/PHPExcel.php');
        $objPHPExcelReader = PHPExcel_IOFactory::load($xls);

        $sheet = $objPHPExcelReader->getSheet(0);        // 读取第一个工作表(编号从 0 开始)  
        $highestRow = $sheet->getHighestRow();           // 取得总行数  
        $highestColumn = $sheet->getHighestColumn();     // 取得总列数  
        $arr = array('A','B','C','D','E','F','G','H','I','J','K','L','M', 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
        // 一次读取一列  
        $res_arr = array();  
        for ($row = 2; $row < $highestRow; $row++) {  
            $row_arr = array();  
            for ($column = 0; !empty($arr[$column]) && $arr[$column] != $highestColumn; $column++) {  
                $val = $sheet->getCellByColumnAndRow($column, $row)->getValue();
                $encode = mb_detect_encoding($val, array("ASCII",'UTF-8',"GB2312","GBK",'BIG5'));
                if($encode!='UTF-8'){
                     $val = mb_convert_encoding($val, 'UTF-8', $encode);
                }
                $row_arr[] = $val;
            }  
              
            $res_arr[] = $row_arr;  
        }  
        return $res_arr;
    }

}

